package com.huajx.tuopuda.client.udp.handler;


import java.io.UnsupportedEncodingException;

import com.huajx.tuopuda.client.udp.TuopudaDirect;
import com.huajx.tuopuda.client.udp.TuopudaException;
import com.huajx.tuopuda.client.udp.TuopudaUtil;
import com.huajx.tuopuda.client.udp.model.Drive;
import com.huajx.util.ByteUtil;
import com.huajx.util.HexUtil;
import com.huajx.util.StrUtil;

/**
 * 配置tuopuda 
 * @author 谭增杰 2019-10-10
 *
 */
public class TcpIpHandler extends AbstractTuopudaHandler {
	private static TcpIpHandler me;
	public static TcpIpHandler me() {
	        if (me == null) {
	            me = new TcpIpHandler();
	        }
	        return me;
	   }

	@Override
	public void send(String ip, int port, int sn) {
		// TODO Auto-generated method stub
		
	}
	
	public void send(String ip,int port,int sn ,Drive drive) throws TuopudaException{
		byte[] byteIp = converByte(ip);//ip字节流 
		byte[] byteGeteWay = converByte(drive.getGateway());//ip字节流 
		byte[] byteMask = converByte(drive.getMask());//ip字节流
		//byte[] byteMac = converByte(drive.getMac());//ip字节流
		byte[] byteMac=HexUtil.hexToBytes(drive.getMac().replace("-", ""));
		sendAndReceive(ip, port,super.encode(sn, TuopudaDirect.D_11F2, (bytes) -> {
	    	 	int checkSum=0;
	            checkSum += TuopudaUtil.replaceBytes(bytes, byteIp, 11, 4);
	            checkSum += TuopudaUtil.replaceBytes(bytes, byteGeteWay, 19, 4);
	            checkSum += TuopudaUtil.replaceBytes(bytes, byteMask, 15, 4);
	            checkSum += TuopudaUtil.replaceBytes(bytes, byteMac, 5, 6);
	            int udp=Integer.parseInt("60000",16);
	            checkSum += TuopudaUtil.replaceBytes(bytes, udp, 23, 2);
	            return checkSum;
	        }));
		
		//return sendAndReceive;
	    
	}
	
	

	public  byte[] converByte(String str){
		if(StrUtil.isBlank(str)){
			return null;
		}
		String[] splits=null;
		if(str.contains("-")){
			splits = str.split("\\-");
		}else {
			splits = str.split("\\.");
		}
		byte[] bytes=new byte[splits.length];
		for (int i=0;i<splits.length;i++) {
			String st=splits[i];
			if(str.contains("-")){
				byte b= (byte)0X7E;
			}else {
				byte[] vbs = ByteUtil.bytesByLength(Integer.parseInt(st,16), 1);
				if(vbs.length>0){
					bytes[i]=vbs[0];
				}
			}
		}
		
		return bytes;
	}

	/*public static void main(String[] args) throws UnsupportedEncodingException {
		byte[] byBuffer = new byte[6];
		String strInput="00574702165c";
		byBuffer= strInput.getBytes("utf-8");
		System.out.println(byBuffer);
	}*/
}
